package com.foxzzz.datamemory.util;


import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;

@Component
public class BlobUtil {
    private final static Logger logger = LoggerFactory.getLogger(BlobUtil.class);
    @Autowired
    private EntityManager entityManager;

    private Session session;

    @PostConstruct
    public void init() {
        entityManager = entityManager.getEntityManagerFactory().createEntityManager();
        session = entityManager.unwrap(Session.class);
    }

    public InputStream getStream(Blob blob) {
        try {
            if (blob != null) {
                return blob.getBinaryStream();
            }
        } catch (SQLException e) {
            logger.error("转化出现错误 {}", e);
        }
        return null;
    }

    public Blob getBlob(InputStream inputStream) {
        if (inputStream != null) {
            try {
                return Hibernate.getLobCreator(session).createBlob(inputStream, inputStream.available());
            } catch (IOException e) {
                logger.error("转化出现错误 {}", e);
            }
        }
        return null;
    }
}
